<template>
  <div class="loginBox">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="用户名" prop="account">
        <el-input v-model="ruleForm.account" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { login } from '@/api/common'
import router from '@/router';

interface RuleForm {
  account: string
  password: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  account: 'mater',
  password: 'yvonne123@'
})

const rules = reactive<FormRules<RuleForm>>({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      login(ruleForm).then((res: any) => {
        if (res.code === 0) {
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('userName', res.data.userName)
          ElMessage.success('登录成功')
          router.push('/')
        } else {
          ElMessage.error(res.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>

<style lang="scss" scoped>
.loginBox {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #20a0ff;

  .el-form {
    background: #fff;
    padding: 40px 80px;
    border-radius: 10px;
  }
  .el-button {
    width: 100%;
  }
}
</style>